package com.container.app.utilities;

import com.container.app.MContainer;
import org.jdom.Element;
import org.jdom.JDOMException;
import org.jdom.input.SAXBuilder;

import java.io.IOException;

import static java.lang.System.getProperty;

/**
 * Created with IntelliJ IDEA.
 * User: Georgiana.Scarlat
 * Date: 7/11/12
 * Time: 12:13 PM
 */

public final class XmlParser {


    /**
     * Parses a xml file into a mapping between pairs of interfaces and annotations and implementations.
     *
     * @param xmlFileName the xml file name
     */
    public static void parseInterfaceAnnotationImplementationMapping(String xmlFileName, MContainer container) throws JDOMException, IOException, ClassNotFoundException {

        Pair<Pair<Class, Pair<Class, String>>, Object> interface_annotation_implementationAssociation;

        Element root = new SAXBuilder().build(getCompleteXMLFilePath(xmlFileName)).getRootElement();

        for (Object interf : root.getChildren("interface")) {

            interface_annotation_implementationAssociation = getElementAssociation((Element) interf);
            container.addMappingToCache(interface_annotation_implementationAssociation);


        }


    }

    /**
     * Obtains an association between interface, annotation and implementation node values from a xml Element.
     *
     * @param element xml Element that contains an interface node with annotation and implementation children.
     * @return association between interface, annotation and implementation node values
     */
    private static Pair<Pair<Class, Pair<Class, String>>, Object> getElementAssociation(Element element) throws ClassNotFoundException {

        Pair<Pair<Class, Pair<Class, String>>, Object> result = null;
        Class interfaceClass, annotationClass;
        Object implementationClass;
        Pair<Class, String> annotation = null;

        interfaceClass = Class.forName(element.getAttributeValue("class"));
        implementationClass = Class.forName(element.getChild("implementation").getAttributeValue("class"));

        Element annotationElement = element.getChild("annotation");
        if (annotationElement != null) {
            annotationClass = Class.forName(annotationElement.getAttributeValue("class"));
            annotation = new Pair<Class, String>(annotationClass, annotationElement.getAttributeValue("value"));
        }

        if (interfaceClass != null && implementationClass != null) {
            Pair<Class, Pair<Class, String>> interface_annotation = new Pair<Class, Pair<Class, String>>(interfaceClass, annotation);
            result = new Pair<Pair<Class, Pair<Class, String>>, Object>(interface_annotation, implementationClass);
        }

        return result;
    }


    private static String getCompleteXMLFilePath(String xmlFileName) {
        return getProperty("user.dir") + "\\xmls\\" + xmlFileName;
    }

}
